//sqlitedb操作
const database = 'ttyl'
export default {
	//打开数据
	openSqlite() {
		return new Promise((resolve, reject) => {
			plus.sqlite.openDatabase({
				name: database, //数据库名称
				path: '_doc/' + database + '.db',
				success(ret) {
					console.log('database is open！')
					resolve(ret); //成功回调
				},
				fail(e) {
					reject(e); //失败回调
					console.log(e)
				}
			})
		})
	},
	//查询数据数据
	selectSql(sql) {
		let _this = this
		//创建表格在executeSql方法里写
		return new Promise((resolve, reject) => {
			plus.sqlite.selectSql({
				name: database,
				//表格创建或者打开，后面为表格结构
				sql: sql,
				success(ret) {
					resolve(ret);
				},
				fail(e) {
					reject(e);
					console.log(e)
				}
			})
		})
	},

	//执行sql语句
	executeSql(sql) {
		let _this = this
		//检测是否连接
		// if(!_this.isOpen()){
		// 	_this.openSqlite()
		// }
		return new Promise((resolve, reject) => {
			//创建表格在executeSql方法里写
			plus.sqlite.executeSql({
				name: database,
				//表格创建或者打开，后面为表格结构
				sql: sql,
				success(ret) {
					resolve(ret); 
					//关闭数据库
					//_this.closeSQL()
				},
				fail(e) {
					reject(e);
					console.log(e)
				}
			})
		})	
	},

	//关闭数据库
	closeSQL() {
		return new Promise((resolve, reject) => {
			plus.sqlite.closeDatabase({
				name: database,
				success(ret) {
					console.log('database is close！')
					resolve(ret);
				},
				fail(e) {
					reject(e);
					console.log(e)
				}
			})
		})
	},

	//监听数据库是否开启
	isOpen(name, path) {
		var database_name = name || database;
		var database_path = path || '_doc/' + database + '.db';
		//数据库打开了就返回true,否则返回false
		var open = plus.sqlite.isOpenDatabase({
			name: database_name,
			path: database_path,
		})
		console.log(open)
		return open
	}
}

